<?php

namespace App\Http\Controllers\Admin;

use App\Models\Images;
use App\Models\Sports;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\NewCat;
use Illuminate\Support\Facades\Validator;

class SportsController extends Controller
{
    /**
     * @var
     */
    public $countrySportsModel;
    protected $countryInCatModel;
    protected $imagesModel;

    /**
     * CountryOutController constructor.
     */
    public function __construct()
    {
        $this->countrySportsModel = new Sports();
        $this->countryInCatModel = new NewCat();
        $this->imagesModel = new Images();
    }
    //
    public function index()
    {
        return view('admin.sports.index');
    }
    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getList(Request $request){
        $params = [
            'where' => [['is_delete', 1]],
            'getfield' => true,
            'order' => 'created_at',
            'field' => ['id', 'title', 'subtitle', 'author', 'source', 'is_check', 'is_hot', 'is_first', 'status', 'created_at','updated_at','key_seo'],
            'page' => $request->get('page'),
            'limit' => $request->get('limit')
        ];
        if(!empty($request->input('title'))){
            $params['where']=array_merge($params['where'],[['title',$request->input('title')]]);
        }
        if(!empty($request->input('is_check'))){
            $params['where']=array_merge($params['where'],[['is_check',$request->input('is_check')]]);
        }
        if(!empty($request->input('is_publish'))){
            $params['where']=array_merge($params['where'],[['status',$request->input('is_publish')]]);
        }
        if(!empty($request->input('start_date')) && !empty($request->input('end_date')) ){
            $params['where']=array_merge($params['where'],[['start_date',[date('Y-m-d H:i:s',strtolower($request->input('start_date'))),date('Y-m-d H:i:s',strtolower($request->input('end_date')))]]]);
        }
        $res = $this->countrySportsModel->getList($params);
        $data = [
            'code' => 0,
            'msg' => '正在请求中...',
            'count' => $res['total'],
            'title'  => !empty($res['row']['title']) ? $res['row']['title'] :'',
            'data' => $res['row']
        ];
        return response()->json($data);
    }
    /**
     *国际新闻添加显示
     */
    public function add()
    {

        return view('admin.sports.add', ['treeCat' => $this->treeSelect()]);
    }

    /**
     * 新闻数据保存
     */
    public function addSave(Request $request)
    {
        $param = $request->input();
        unset($param['file']);
        $validate = [
            //规则
            'rule' => [
                'title' => 'required|string|between:0,200',
                'subtitle' => 'required',
                'newcat_id' => 'required|integer',
                'key_seo' => 'required|string|between:0,300',
                'key_description' => 'required|string|min:0|max:400',
                //'content' => 'required',
                'author' => 'required|string|between:0,20',
                'source' => 'required|string|between:0,20',
                'images' => 'required',
            ],
            //提示信息
            'message' => [
                'title.required' => '标题名称不能为空',
                'title.string' => '标题名称仅支持字符串',
                'title.between' => '标题名称长度介于０-200个字符',
                'subtitle.required' => '副标题名称不能为空',
                'newcat_id.required' => '请选择所属分类',
                'newcat_id.integer' => '所属分类必须是数字型',
                'key_seo.required' => '关键字不能为空',
                'key_seo.string' => '关键字必须是字符串',
                'key_seo.between' => '关键字0-300之间',
                //'content.required' => '内容不能为空',
                'author.required' => '作者不能为空',
                'author.string' => '作者必须是字符型',
                'author.between' => '作者必须在0-20个字符',
                'source.required' => '来源不能为空',
                'source.string' => '来源必须是字符串',
                'source.between' => '来源必须在0-20个字符之间',
                'images.required' => '新闻图片不能为空',

            ],
            //自定义
            'custom' => [
                'title' => '标题名称',
                'subtitle' => '副标题',
                'newcat_id' => '所属分类',
                'key_seo' => '关键字',
                'key_description' => '新闻描述',
                //'content' => '新闻内容',
                'author' => '作者',
                'source' => '来源',
                'images' => '默认图片',
            ]
        ];
        $validator = Validator::make( $request->all(), $validate['rule'], $validate['message'], $validate['custom'] );
        if ($validator->fails()) {
            return response()->json([ 'code'=>'300', 'msg' => $validator->errors()->first() ]);
        }
        //调用模型插入数据
        $rs = $this->countrySportsModel->addCountrySports($param);
        if($rs){
            return response()->json(array('code'=>200,'msg'=>'保存成功'));
        }else{
            return response()->json(array('code'=>300,'msg'=>'保存失败'));
        }
    }

    /**
     *删除国际新闻
     */
    public function delCountrySports(Request $request){

        $id = $request->input('id');
        if(empty($id) || !is_numeric($id)){
            return response()->json(array('code'=>300,'msg'=>"参数为空"));exit;
        }
        $rs = $this->countrySportsModel->oneFind(['id'=>$id,'is_delete'=>1]);
        if($rs && $rs->status==1){
            return response()->json(array('code'=>300,'msg'=>"新闻正常显示，请屏蔽后删除"));exit;
        }
        $arr = [
            'where'=>[['id',$id]],
            'field'=>['is_delete'=>2]
        ];
        $res = $this->countrySportsModel->updateCountrySports($arr);
        if($res){
            return response()->json(array('code'=>200,'msg'=>'删除成功'));
        }else{
            return response()->json(array('code'=>300,'msg'=>'删除失败'));
        }

    }

    /**
     * 国际新闻编辑加载
     * @param Request $request
     * @param $arg1
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function editCountrySports(Request $request,$arg1){
        $id =  $request->route('id');
        if(empty($id) || !is_numeric($id)){
            return response()->json(array('code'=>300,'msg'=>"参数为空"));exit;
        }
        $arr = ['id'=>$id];
        $res = $this->countrySportsModel->oneFind($arr);
        $params = [
            'where' => [['id', $res->images]],
            'field' => ['id','img_url'],

        ];
        $img_rs= $this->imagesModel->findOne($params);
        $res->images = $img_rs->img_url;
        return view('admin.sports.edit',['result'=>objectToArray($res),'treeCat'=>$this->treeSelect(),'countryInRecommend'=>countryInRecommend(),'countryInFirst'=>countryInFirst()]);
    }

    /**
     *编辑器图片上传
     */
    public function layeditUpload(Request $request){
        $file = $request->file('file');
        $url_path = 'uploads/cover';
        $rule = ['jpg', 'png', 'gif'];
        if ($file->isValid()) {
            $clientName = $file->getClientOriginalName();
            $tmpName = $file->getFileName();
            $realPath = $file->getRealPath();
            $entension = $file->getClientOriginalExtension();
            if (!in_array($entension, $rule)) {
                return '图片格式为jpg,png,gif';
            }
            $newName = md5(date("Y-m-d H:i:s") . $clientName) . "." . $entension;
            $path = $file->move($url_path, $newName);
            $namePath = $url_path . '/' . $newName;
            $res = [
                'code'=>0,
                'msg'=>'',
                'data'=>[
                    'src'=>'',
                    'title'=>''
                ]
            ];
            return response()->json($res);
        }

    }

    /**
     * 国际新闻编辑保存
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function editSave(Request $request){
        $params=[
            'where'=>[['id',$request->input('id')]],
            'field'=>[
                'title'             =>$request->input('title'),
                'subtitle'          =>$request->input('subtitle'),
                'newcat_id'         =>$request->input('newcat_id'),
                'key_seo'           =>$request->input('key_seo'),
                'key_description'   =>$request->input('key_description'),
                'info'              =>$request->input('info'),
                'content'           =>$request->input('content'),
                'title_attr'        =>$request->input('title_attr'),
                'title_color'       =>$request->input('title_color'),
                'created_at'        =>$request->input('created_at'),
                'author'            =>$request->input('author'),
                'source'            =>$request->input('source'),
                'is_check'          =>$request->input('is_check'),
                'title_url'         =>$request->input('title_url'),
                'is_hot'            =>$request->input('is_hot'),
                'is_first'          =>$request->input('is_first'),
                'images'            =>$request->input('images'),
                'updated_at'        =>date('Y-m-d H:i:s',time())
            ]
        ];
        $res = $this->countrySportsModel->updateCountrySports($params);
        if($res){
            return response()->json(array('code'=>200,'msg'=>'编辑成功'));
        }else{
            return response()->json(array('code'=>300,'msg'=>'编辑失败'));
        }
    }

    /**
     * 国际新闻审核
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function isCheck(Request $request){
        $params=[
            'where'=>[['id',$request->input('id')]],
            'field'=>[
                'is_check'=>$request->input('is_check')
            ]
        ];
        $res = $this->countrySportsModel->updateCountrySports($params);
        if($res){
            return response()->json(array('code'=>200,'msg'=>'审核成功'));
        }else{
            return response()->json(array('code'=>300,'msg'=>'审核失败'));
        }
    }

    /**
     * 是否发布
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function isStatus(Request $request){
        $params=[
            'where'=>[['id',$request->input('id')]],
            'field'=>[
                'status'=>$request->input('status')
            ]
        ];
        $res = $this->countrySportsModel->updateCountrySports($params);
        if($res){
            return response()->json(array('code'=>200,'msg'=>'发布成功'));
        }else{
            return response()->json(array('code'=>300,'msg'=>'发布失败'));
        }
    }

    /**
     * @return array
     */
    private function treeSelect(){
        $params = [
            'where' => [['is_delete', 1]],
            'field' => ['id', 'pid', 'title'],
            'getfield' => true,
            'getcount'=>false,
            'order' => 'created_at'
        ];
        $res = $this->countryInCatModel->getlist($params);
        $tree_node = treeNode(objectToArray($res['row']));
        return $tree_node;
    }
}
